package com.nishop.web.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.common.base.Splitter;
import com.nishop.api.common.CharacterConstant;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.nishop.api.common.NiShopConstant;

import java.util.List;

/**
 * 登录拦截器
 * 
 * @author liuwenlai
 *
 */
public class LoginInterceptor implements HandlerInterceptor {

	private String sessionTimeoutUrl = "/login";

	private Logger logger = LoggerFactory.getLogger(LoginInterceptor.class);

	@Value("${nishop.login.ignore.urls}")
	private String ignoreUrls;

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
			Object handler) throws Exception {

//		if(){
//
//		}

		Object login_token = request.getSession().getAttribute(NiShopConstant.LOGIN_TOKEN);
		logger.info("login token : " + login_token);
		logger.info("request url : " + request.getRequestURL().toString());

		if (login_token != null) {
			return true;
		}

		response.sendRedirect(request.getServletContext().getContextPath() + "/login");

		return false;
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response,
			Object handler, Exception ex) throws Exception {
		HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
	}

	public void setSessionTimeoutUrl(String sessionTimeoutUrl) {
		this.sessionTimeoutUrl = sessionTimeoutUrl;
	}

	public String getSessionTimeoutUrl() {
		return sessionTimeoutUrl;
	}

	private boolean isIgnoreUrl(String url){
		List<String> ignoreUrlList = Splitter.on(CharacterConstant.CHARACTER_COMMA_EN).splitToList(ignoreUrls);
		AntPathMatcher matcher = new AntPathMatcher();
		for (String pattern:ignoreUrlList){
			if(matcher.match(pattern,url)){
				return true;
			}
		}
		return false;
	}
}
